#include "app_message.h"
#include "log/log.h"
#include "cJSON/cJSON.h"
#include "string.h"
#include "stdlib.h"
#include "app_common.h"

char *app_message_bytes_to_json(char *bytes, int bytes_len)
{
    char connection_type = bytes[0];
    char id_len = bytes[1];
    char msg_len = bytes[2];

    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, "conn_type", connection_type);
    char id_bytes[id_len];
    char msg_bytes[msg_len];
    memcpy(id_bytes, bytes + 3, id_len);
    memcpy(msg_bytes, bytes + 3 + id_len, msg_len);
    
    //把字节数组转换16进制的字符串
    char *id_json_str = app_common_bytes2hexstr(id_bytes, id_len);
    char *msg_json_str = app_common_bytes2hexstr(msg_bytes, msg_len);

    cJSON_AddStringToObject(json, "id", id_json_str);
    cJSON_AddStringToObject(json, "msg", msg_json_str);

    char *json_str = cJSON_PrintUnformatted(json);
    cJSON_Delete(json);
    return json_str;
    
}

int app_message_json_to_bytes(char *json, char *bytes_buff, int buff_len)
{
       // 1 解析json字符串
       cJSON *json_obj = cJSON_Parse(json);
       if (json_obj == NULL)
       {
           log_error("json解析失败");
       }
       // 2 提取json中的字段
       cJSON *conn_type_json = cJSON_GetObjectItem(json_obj, "conn_type");
       cJSON *id_json = cJSON_GetObjectItem(json_obj, "id");
       cJSON *msg_json = cJSON_GetObjectItem(json_obj, "msg");
   
       // 3 提取到临时变量
       char conn_type = conn_type_json->valueint;
       int id_len = strlen(id_json->valuestring) / 2;
       int msg_len = strlen(msg_json->valuestring) / 2;
   
       // 4 把16进制的字符串转换成字节数组
       char id_bytes[id_len];
       char msg_bytes[msg_len];
       id_len = app_common_hexstr2bytes(id_json->valuestring, id_bytes);
       msg_len = app_common_hexstr2bytes(msg_json->valuestring, msg_bytes);
       // 5 最终组成字节数组
       int bytes_len = id_len + msg_len + 3;
       if(buff_len < bytes_len)
       {
           log_error("bytes_buff 缓冲空间不足");
           return -1;
       }
       bytes_buff[0] = conn_type;
       bytes_buff[1] = id_len;
       bytes_buff[2] = msg_len;
       memcpy(bytes_buff + 3, id_bytes, id_len);
       memcpy(bytes_buff + 3 + id_len, msg_bytes, msg_len);
       return bytes_len;
   
}
